package com.bzyd.cloud.listener;

import com.bzyd.cloud.dao.TxLogDao;
import com.bzyd.cloud.pojo.Order;
import com.bzyd.cloud.pojo.TxLog;
import com.bzyd.cloud.service.impl.OrderServiceImpl4;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

/**
 * Created by Xianyue Dang on 2021/8/20
 */
@Service
@RocketMQTransactionListener(txProducerGroup = "tx_producer_group")
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private OrderServiceImpl4 orderServiceImpl4;

    @Autowired
    private TxLogDao txLogDao;

    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        String txId = (String) msg.getHeaders().get("txId");
        System.out.println("操作数据库，执行实际业务");
        try {
            //本地事务（创建订单或者是支付成功后修改订单状态）
            Order order = (Order) arg;
            orderServiceImpl4.createOrder(txId, order);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    //消息回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String txId = (String) msg.getHeaders().get("txId");
        TxLog txLog = txLogDao.findById(txId).get();
        if (txLog != null) {
            //本地事务，订单成功了
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
